<template>
  <div class="menu-view" :class="{ 'split-view': isInSplitScreen, [`position-${position}`]: position }">
    <div class="page-content">
      <!-- 有URL的组件 -->
      <template v-if="meta.url">
        <component
          v-if="currentComponent"
          :is="currentComponent"
        />
        <div v-else class="loading-state">
          <el-skeleton :rows="6" animated />
        </div>
      </template>
      <!-- 无URL时显示简单的空状态 -->
      <template v-else>
        <el-empty description="暂无内容">
          <template #description>
            <p>菜单ID: {{ meta.menuId || meta.id || '未知' }}</p>
            <p>菜单名称: {{ meta.title || meta.name || '未知' }}</p>
          </template>
        </el-empty>
      </template>
    </div>
  </div>
</template>

<script setup>
import { computed, ref, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'

// 接收props参数
const props = defineProps({
  currentMenuPath: String,
  position: String
});

const route = useRoute()
const router = useRouter()
const currentComponent = ref(null)

// 检查是否在分屏模式下
const isInSplitScreen = computed(() =>
  route.matched.some(record => record.path === '/split-screen')
)

// 获取当前路径 - 优先使用props传入的路径
const currentPath = computed(() => {
  // 1. 优先使用props传入的路径
  if (props.currentMenuPath) {
    console.log(`Using props currentMenuPath: ${props.currentMenuPath}`)
    return props.currentMenuPath
  }

  // 2. 如果是分屏模式，则根据position获取对应的路径
  if (isInSplitScreen.value) {
    if (props.position === 'left' && router.leftMenuPath) {
      console.log(`Using router.leftMenuPath: ${router.leftMenuPath}`)
      return router.leftMenuPath
    }

    if (props.position === 'right' && router.rightMenuPath) {
      console.log(`Using router.rightMenuPath: ${router.rightMenuPath}`)
      return router.rightMenuPath
    }

    // 从路由查询参数中获取
    const { left, right } = route.query
    if (props.position === 'left' && left) {
      console.log(`Using route.query.left: ${left}`)
      return left
    }

    if (props.position === 'right' && right) {
      console.log(`Using route.query.right: ${right}`)
      return right
    }
  }

  // 3. 回退到当前路由路径
  console.log(`Using current route.path: ${route.path}`)
  return route.path
})

// 获取元数据
const meta = computed(() => {
  // 1. 如果在分屏模式下
  if (isInSplitScreen.value) {
    const path = currentPath.value
    // 查找对应的路由
    const matchedRoute = router.getRoutes().find(route => route.path === path)
    if (matchedRoute) {
      console.log(`Found matched route meta for path ${path}:`, matchedRoute.meta)
      return matchedRoute.meta || {}
    }
  }

  // 2. 回退到当前路由元数据
  return route.meta || {}
})

// 使用 Vite 的 import.meta.glob 动态导入组件
// 预加载所有 views 目录下的组件
const componentModules = import.meta.glob('../views/**/*.vue')

// 安全地使用store的函数
async function safeUseStore() {
  try {
    const module = await import('../stores/menuStore')
    return module.useMenuStore()
  } catch (error) {
    console.error('加载菜单存储失败:', error)
    return null
  }
}

// 加载组件
const loadComponent = async () => {
  try {
    // 清除旧组件
    currentComponent.value = null

    const path = currentPath.value
    console.log(`Loading component for path: ${path}, meta:`, meta.value)

    if (!meta.value.url) {
      console.log('当前菜单没有URL，显示空状态', meta.value)
      return
    }

    // 根据URL加载组件
    let component = null
    const url = meta.value.url
    console.log('加载组件URL:', url)

    // 处理URL，移除开头的斜杠和结尾的.vue（如果有）
    let processedUrl = url
    if (processedUrl.startsWith('/')) {
      processedUrl = processedUrl.substring(1)
    }
    if (processedUrl.endsWith('.vue')) {
      processedUrl = processedUrl.substring(0, processedUrl.length - 4)
    }

    let componentPath = ''

    // 根据 URL 构建可能的组件路径
    const possiblePaths = [
      // 常规匹配尝试
      `../views/${processedUrl}.vue`,
    ].filter(Boolean); // 过滤掉 null 值

    console.log('尝试的组件路径:', possiblePaths);

    // 尝试每个可能的路径
    for (const path of possiblePaths) {
      console.log('检查路径:', path, '是否存在:', !!componentModules[path]);
      if (componentModules[path]) {
        componentPath = path;
        console.log('找到匹配的组件路径:', path);
        break;
      }
    }

    // 如果没有找到匹配路径，尝试遍历所有可用模块查找最接近的匹配
    if (!componentPath) {
      console.log('未找到精确匹配，尝试模糊匹配');
      const urlParts = processedUrl.split('/');
      const lastPart = urlParts[urlParts.length - 1];

      // 尝试查找包含最后一部分的路径
      for (const path in componentModules) {
        if (path.includes(lastPart)) {
          console.log('找到模糊匹配:', path);
          componentPath = path;
          break;
        }
      }
    }

    // 如果找到了组件
    if (componentPath) {
      component = await componentModules[componentPath]();
      console.log('成功加载组件:', componentPath);
    } else {
      console.warn('未找到匹配的组件，使用占位符');
      // 未找到组件，使用占位符
      component = {
        template: `
          <div class="component-placeholder">
            <h3>未实现的组件</h3>
            <p>组件URL: ${url}</p>
            <p>尝试的路径: ${possiblePaths.join(', ')}</p>
          </div>
        `
      }
    }

    currentComponent.value = component.default || component
  } catch (error) {
    console.error(`加载组件失败:`, error)
    currentComponent.value = {
      template: `<div class="component-error">加载失败: ${error.message}</div>`
    }
  }
}

// 监听路由和路径变化
watch(
  [
    () => route.path,
    () => meta.value.url,
    () => props.currentMenuPath,
    () => props.position
  ],
  loadComponent,
  { immediate: true }
)

// 组件挂载时加载
onMounted(loadComponent)
</script>

<style scoped>
.menu-view {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.menu-view.split-view {
  padding: 0;
}

.menu-view.split-view.position-left {
  border-right: 1px solid #e6e6e6;
}

.menu-view.split-view.position-right {
  border-left: 1px solid #e6e6e6;
}

.page-content {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  flex: 1;
  overflow: auto;
}

.loading-state,
.component-placeholder,
.component-error {
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.component-error {
  background-color: #fff0f0;
}

.component-placeholder {
  background-color: #f8f9fa;
}
</style>
